//
//  YWDoNoEquipmentTroubleMissionViewController.m
//  maintain
//
//  Created by Kyo on 16/9/13.
//  Copyright © 2016年 ewin. All rights reserved.
//

#import "YWDoNoEquipmentTroubleMissionViewController.h"
#import "UIColor+CustomColors.h"
#import "YWCommonTool.h"
#import "YWMacro.h"
#import "YWConst.h"
#import "YWLoginTool.h"
#import "YWLoginUser.h"
#import "YWHandler.h"

//#import "YWImageView.h"
#import "YWPhotoView.h"
//#import "YWAlertView.h"
#import "YWWriteNoteCell.h"
#import "YWTakePhotoCell.h"

#import "YWMission.h"
#import "YWResourceManager.h"
#import "YWMissionManager.h"
#import "YWEquipmentTroubleRecord.h"
#import "YWCirculationInfo.h"
#import "YWCirculationManager.h"
#import "YWNotifyManager.h"
#import "YWEquipment.h"
#import "YWReportTroubleModel.h"
#import "YWTroubleMissionModel.h"
#import "YWTroubleMissionManager.h"

@interface YWDoNoEquipmentTroubleMissionViewController ()<YWTakePhotoCellDelegate,YWWriteNoteCellDelegate>
@property (nonatomic, strong) UIView *footView;
@property (nonatomic, copy) NSString *note;
@property (nonatomic, strong) NSArray *totalImageNameArray;
//扫描进入任务页面时的时间
@property (nonatomic, assign) NSTimeInterval clientScanTime;
@end

@implementation YWDoNoEquipmentTroubleMissionViewController

- (instancetype)init{
    return [super initWithStyle:UITableViewStyleGrouped];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = NSLocalizedString(@"trouble", nil);//@"维修";
    self.view.backgroundColor = [UIColor customBackgroudColor];
    
    _clientScanTime = [[NSDate date] timeIntervalSince1970]*1000;
    self.tableView.backgroundColor = [UIColor customBackgroudColor];
    self.tableView.separatorColor = [UIColor customLineColor];
    self.tableView.sectionFooterHeight = 1.0;
    self.tableView.tableFooterView = self.footView;
    
    [self.tableView registerClass:[YWWriteNoteCell class] forCellReuseIdentifier:YWWriteNoteCellIdentifier];
    [self.tableView registerClass:[YWTakePhotoCell class] forCellReuseIdentifier:YWTakePhotoCellIdentifier];
    
    if (self.troubleMissionModel.trouble.qrcodeId.length==0) {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"noQrcodeTroubleTips", nil) message:NSLocalizedString(@"noQrcodeTroubleTips", nil) preferredStyle:UIAlertControllerStyleAlert];
        [alert addAction:[UIAlertAction actionWithTitle:@"知道了" style:UIAlertActionStyleCancel handler:nil]];
        [self presentViewController:alert animated:YES completion:nil];
    }
}

#pragma mark - Table view data source
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 1){
        CGFloat imageH = YWPhotoSize*(self.totalImageNameArray.count/4+1) + YWPhotoGap*(self.totalImageNameArray.count/4);
        return 10*2 + imageH;
    }else{
        return 90;
    }
    
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section==0){
        YWWriteNoteCell *cell = [tableView dequeueReusableCellWithIdentifier:YWWriteNoteCellIdentifier];
        cell.delegate = self;
        return cell;
        
    }else if (indexPath.section==1){
        YWTakePhotoCell *cell = [tableView dequeueReusableCellWithIdentifier:YWTakePhotoCellIdentifier];
        cell.delegate = self;
        cell.totalImageNameArray = self.totalImageNameArray;
        return cell;
    }
    
    return [[UITableViewCell alloc] init];
}

- (UIView*)tableView:(UITableView*)tableView viewForHeaderInSection:(NSInteger)section
{
    static NSString* HeaderIdentifier = @"YWDoNoEquipmentTroubleMissionTableViewControllerForHeaderInSection";
    UITableViewHeaderFooterView* headerView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:HeaderIdentifier];
    if (headerView == nil) {
        headerView = [[UITableViewHeaderFooterView alloc] initWithReuseIdentifier:HeaderIdentifier];
        UILabel* label = [[UILabel alloc] init];
        label.textAlignment = NSTextAlignmentLeft;
        label.textColor = [UIColor customTextGrayColor];
        label.tag = 2006;
        label.numberOfLines = 0;
        label.font = KSmallContentFont;
        [headerView addSubview:label];
    }
    NSString *headText = [self titleForHeaderInSection:section];
    UILabel* label = [headerView viewWithTag:2006];
    label.text = headText;
    label.frame = CGRectMake(15, 0, SCREEN_WIDTH - 2 * 15, 35);
    return headerView;
}

-(NSString *)titleForHeaderInSection:(NSInteger)section{
    if (section==0){
        return NSLocalizedString(@"note", nil);//@"备注";
    }else if (section==1){
        return NSLocalizedString(@"takePhotoToUpload", nil);//@"拍照上传";
    }
    return nil;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 35;
}

#pragma mark - YWTakePhotoCellDelegate
- (void)resetCellFrameWithImages:(NSArray *)images cell:(UITableViewCell *)cell{
    NSArray* arr = [[NSArray alloc] initWithArray:images copyItems:YES];
    self.totalImageNameArray = arr;
    
    [self.tableView reloadData];
}
#pragma mark - YWWriteNoteCellDelegate
- (void)passNote:(NSString *)note{
    _note = note;
}
- (void)commintRecord{
    [self.view endEditing:YES];
    if (_note.length == 0) {
        [YWCommonTool showTextHUDWithContent:NSLocalizedString(kTextTroubleDescriptionNotNull, nil)];
        return;
    }
    if ([YWCommonTool isContainsEmoji:_note]) {
        [YWCommonTool showTextHUDWithContent:NSLocalizedString(kTextCantContainEmoji, nil)];
        return;
    }
    if (_note.length > 100) {
        [YWCommonTool showTextHUDWithContent:NSLocalizedString(kTextTroubleDescriptionMax, nil)];
        return;
    }
    UIAlertController* alertController= [UIAlertController alertControllerWithTitle:NSLocalizedString(@"tips", nil) message:NSLocalizedString(kTextConfirmSubmitMission, nil) preferredStyle:UIAlertControllerStyleAlert];
    [alertController addAction:[UIAlertAction actionWithTitle:NSLocalizedString(@"cancel", nil) style:UIAlertActionStyleCancel handler:nil]];
    [alertController addAction:[UIAlertAction actionWithTitle:NSLocalizedString(@"sure", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        _troubleMissionModel.updateTime = [[NSDate date] timeIntervalSince1970] * 1000;
//        _troubleMission.updateTime = _troubleMission.finishTime;
        _troubleMissionModel.troubleStatus = YWTroubleMissionStatusFinish;
        _troubleMissionModel.read = YES;
        __block NSArray* pictures = [self createPicturesWithTroubleMission];
        __block YWEquipmentTroubleRecord* troubleRecord = [self createEquipmentTroubleRecord];
        //__block NSArray *equipmentFieldRecords = nil;
        
//        BOOL saveMission = [[YWMissionManager shareManager] saveTroubleMissionWithMissionArray:_troubleMission?@[ _troubleMission ]:nil];
        BOOL saveMission = [[YWTroubleMissionManager shareManager] updateTroubleMissionWithArray:_troubleMissionModel?@[_troubleMissionModel]:nil needUpdateReportTrouble:NO];
        
        BOOL saveTroubleRecord = [[YWTroubleMissionManager shareManager] updateTroubleRecord:troubleRecord];
        BOOL savePicturesToDB = [[YWResourceManager shareManager] savePicturesToDBWithArray:pictures];
        //BOOL saveEquipmetFieldRecord = [[YWMissionManager shareManager] updateEquipmentFieldRecords:equipmentFieldRecords];
        if (saveMission && saveTroubleRecord && savePicturesToDB && troubleRecord) {
            //创建保存流转信息
            [[YWCirculationManager shareManager] createAndSaveLocalCirculationInfoWithType:YWCirculationInfoTypeFinishTroubleMission troubleId:_troubleMissionModel.trouble.troubleId recipient:nil note:nil];
            
            [[YWTroubleMissionManager shareManager] startUploadTroubleMissionRecords:@[troubleRecord] troubleMissionModel:_troubleMissionModel pictures:pictures];
            
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [[YWNotifyManager shareManager] postMissionFinishedNotifyWithMission:_troubleMissionModel];
                [self.navigationController popViewControllerAnimated:YES];
            });
        }else {
            YWLog(@"保存数据库失败");
            [YWCommonTool showTextHUDWithContent:NSLocalizedString(kTextSubmitTaskFail, nil)];
        }
    }]];
    [self presentViewController:alertController animated:YES completion:nil];
}

- (NSArray*)createPicturesWithTroubleMission
{
    NSMutableArray* pictures = [NSMutableArray array];
    for (int i = 0; i < [self.totalImageNameArray count]; i++) {
        YWPicture* picture = [[YWPicture alloc] init];
        picture.pictureId = [YWCommonTool randStringId];
        picture.pictureName = self.totalImageNameArray[i];
        picture.isLocalImage = YES;
        picture.uploadStatus = YWPictureUploadStatusNull;
        picture.missionId = _troubleMissionModel.trouble.troubleId;
        picture.maintenanceType = _troubleMissionModel.trouble.maintenanceTypeId;
        picture.equipmentId = _troubleMissionModel.trouble.equipment.equipmentId;
        picture.pictureTroubleType = YWPictureTroubleTypeRecord;
        [pictures addObject:picture];
    }
    return pictures;
}

- (YWEquipmentTroubleRecord*)createEquipmentTroubleRecord
{
    YWEquipmentTroubleRecord* troubleRecord = [[YWEquipmentTroubleRecord alloc] init];
    troubleRecord.recordId = [YWCommonTool randNumber];
    /**任务ID*/
    troubleRecord.missionId = _troubleMissionModel.trouble.troubleId;
    NSString *uniqueTag = [YWCommonTool randStringId];//[NSString stringWithFormat:@"%ld",(long)troubleRecord.recordId] ;
    troubleRecord.uniqueTag = uniqueTag;
    troubleRecord.equipmentId = _troubleMissionModel.trouble.equipment.equipmentId;
    troubleRecord.note = _note;
    troubleRecord.completeTime = [[NSDate date] timeIntervalSince1970] * 1000;
    troubleRecord.clientScanTime = _clientScanTime;
    troubleRecord.handlerName = [YWLoginTool loginUser].userName;
    troubleRecord.reasonId = 0;
    troubleRecord.replacementStatus = YWRecordReplacementStatusNO;
    troubleRecord.replacementName = nil;
    ;
    troubleRecord.recordType = YWMalfunctionRecordTypeFixed;
    troubleRecord.uploadStatus = YWEquipmentMaintenanceRecordUploadStatusUploading;
    troubleRecord.equipmentTypeId = 0;//_currentEquipment.equipmentTypeId;
    
    troubleRecord.reporterName = _troubleMissionModel.trouble.reporter.userName;
    troubleRecord.reporterNumber = _troubleMissionModel.trouble.reporter.mobile;
    troubleRecord.reportNote = _troubleMissionModel.trouble.note;
    troubleRecord.reportTime = _troubleMissionModel.trouble.reportTime;
    troubleRecord.maintenanceTypeId = YWMaintenanceTypeTrouble;
    
    NSString *dayMonthString = [YWCommonTool showTime:troubleRecord.completeTime / 1000 andFormatter:KTimeFormatDayMonth];
    troubleRecord.dayMonthString = dayMonthString;
    troubleRecord.laborCosts = nil;
    troubleRecord.materialCosts = nil;
    return troubleRecord;
}

- (UIView *)footView{
    if (!_footView) {
        UIView * footView = [[UIView alloc] init];
        footView.frame = CGRectMake(0, 0, SCREEN_WIDTH, kButtonH+30*2);
        footView.backgroundColor = [UIColor customBackgroudColor];
        _footView = footView;
        CGFloat buttonWidth = SCREEN_WIDTH-20*2;
        
        UIButton *button = [[UIButton alloc] init];
        button.layer.masksToBounds = YES;
        button.layer.cornerRadius = 4.0;
        
        button.frame = CGRectMake(20, 30, buttonWidth, kButtonH);
        [button setTitle:NSLocalizedString(@"commit", nil) forState:UIControlStateNormal];
        [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        button.backgroundColor = [UIColor customBlueColor];
        [button addTarget:self action:@selector(commintRecord) forControlEvents:UIControlEventTouchUpInside];
        [_footView addSubview:button];
    }
    return _footView;
}
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    [self.view endEditing:YES];
}
@end
